#!/usr/bin/python -u
#
# This program is copyright (c) 2009 Artur Kaszuba.
# Feedback and improvements are welcome.
#
# THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
# MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307  USA.

statfile='/proc/meminfo'

import os, sys, commands, re

version = "0.1"

# Define options
from optparse import OptionParser
parser = OptionParser(	usage="usage: %prog [options]",
			version="%prog: " + version,
			description="SNMP Feeder module to stat iptables rules")
parser.add_option("--save",
		action="store_true",
		dest="save",
		help="Save stats to stdout")
(options, args) = parser.parse_args()

# Define statistic line
cmp_line=re.compile(r"""^([a-zA-Z0-9]*):\s*    # Name
		([0-9]*)\s*                    # kBytes
		kB\s*                          #
		""", re.VERBOSE)


def AnalyzeStatLine(line):
	if cmp_line.match(line):
		m = cmp_line.match(line)
		tmp = {}
		tmp['name'] = m.group(1)
		tmp['bytes'] = m.group(2)
		return tmp

def GetStats():
	if os.path.exists(statfile):
		f=open(statfile, 'r')
	else:
		return
	out={}
	for line in f:
		tmp = AnalyzeStatLine(line)
		if isinstance(tmp, dict):
			out[ tmp['name'] ] = tmp['bytes']
	return out

def ReadModuleConfig(filename):
	"""Read configuration file"""
	from configobj import ConfigObj
	if os.path.exists(filename):
		conf = ConfigObj(filename)
	else:
		print "Missing config file %s" % filename
		sys.exit(1)
	return conf

config = ReadModuleConfig('/etc/snmp-feeder/modules/meminfo')

# Check options
if options.save:
	stats=GetStats()
#	print stats
	print "%s %s %s %s %s %s %s %s %s %s %s %s %s %s" % (\
		stats['MemTotal'],
		stats['MemFree'],
		stats['Buffers'],
		stats['Cached'],
		stats['SwapCached'],
		stats['Active'],
		stats['Inactive'],
		stats['SwapTotal'],
		stats['SwapFree'],
		stats['Dirty'],
		stats['Writeback'],
		stats['AnonPages'],
		stats['Mapped'],
		stats['Slab'],
		)
